import 'dart:async';

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import 'package:heven/state/music.dart';

class MusicPlayer extends StatefulWidget {
  const MusicPlayer({super.key});

  @override
  _MusicPlayerState createState() => _MusicPlayerState();
}

class _MusicPlayerState extends State<MusicPlayer> {
  bool _isPlayProgress = false;
  Duration duration = Duration.zero;
  Duration position = Duration.zero;
  double progress = 0.0;
  Map<String, String>? currentSong;
  var music;

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _isPlayProgress = true;
    Timer(const Duration(milliseconds: 300), () {
      music = context.read<MusicState>();
      print(36666);
      print(music.currentSong);
      final audioPlayer = music.audioPlayer;
      currentSong = music.currentSong;
      print(currentSong);

      // 监听音频状态变化
      audioPlayer.onDurationChanged.listen((d) {
        print("duration");
        duration = d;
        setState(() {
          duration = d;
          print(duration);
          print("durationEnd");
        });
      });

      // 监听音频位置变化
      audioPlayer.onPositionChanged.listen((pos) {
        if (_isPlayProgress) {
          setState(() {
            position = pos;
            progress = (pos.inMilliseconds.toDouble() / duration.inMilliseconds)
                .clamp(0.0, 1.0);
          });
        }
      });

      // 监听音频播放完成事件
      audioPlayer.onPlayerComplete.listen((_) {
        nextSong(); // 播放下一首
      });

      playAudio();
    });
  }

  @override
  void dispose() {
    _isPlayProgress = false;
    _scrollController.dispose();
    super.dispose();
  }

  void playAudio() {
    print(0123654);
    print(currentSong);
    if (currentSong != null) {
      music.playSong(currentSong!);
    }
  }

  void pauseAudio() {
    music.pauseSong();
  }

  void nextSong() {
    final playlist = music.playlist;
    final currentSongIndex = music.findIndexById();
    print(currentSong);
    print(currentSongIndex);
    if (playlist.isNotEmpty) {
      final nextIndex = (currentSongIndex + 1) % playlist.length;
      final nextSong = playlist[nextIndex];
      WidgetsBinding.instance.addPostFrameCallback((_) {
        music.playSong(nextSong);
        print(100000000000000100);
      });
    }
  }

  void previousSong() {
    final playlist = music.playlist;
    final currentSongIndex = music.findIndexById();

    if (playlist.isNotEmpty) {
      final prevIndex =
          (currentSongIndex == 0) ? playlist.length - 1 : currentSongIndex - 1;
      final prevSong = playlist[prevIndex];
      WidgetsBinding.instance.addPostFrameCallback((_) {
        music.playSong(prevSong);
      });
    }
  }

  void seekToPosition(Duration newPos) async {
    music.seekToPosition(newPos);
  }

  @override
  Widget build(BuildContext context) {
    final currentSong = context.watch<MusicState>().currentSong;
    final isPlaying = context.watch<MusicState>().isPlaying;
    final lyrics = currentSong?['lyric']?.split('\r') ?? [];

    if (currentSong == null) {
      return const Center(child: Text('未选中歌曲'));
    }

    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomLeft,
          colors: <Color>[Color(0xFF060606), Color(0xFF145221)],
        ),
      ),
      child: ListView(
        controller: _scrollController,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0),
            ),
            padding: const EdgeInsets.fromLTRB(44, 10, 44, 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10.0),
              child: CachedNetworkImage(
                imageUrl: currentSong['image_url']!,
                placeholder: (context, url) =>
                    const CircularProgressIndicator(),
                errorWidget: (context, url, error) => const Icon(Icons.error),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 19, right: 19),
            child: Text(
              currentSong['title']!,
              style: const TextStyle(
                  color: Colors.white, fontSize: 17, height: 1.5),
            ),
          ),
          Slider(
            value: progress,
            min: 0,
            max: 1,
            activeColor: Colors.white,
            inactiveColor: const Color(0xFFA1A1A1),
            onChanged: (double newProgress) {
              final clampedProgress = newProgress.clamp(0.0, 1.0);
              final newPos = Duration(
                milliseconds:
                    (clampedProgress * duration.inMilliseconds).toInt(),
              );
              seekToPosition(newPos);
              setState(() {
                progress = clampedProgress;
              });
            },
          ),
          Padding(
            padding: const EdgeInsets.only(left: 19, right: 19),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '${position.inMinutes}:${(position.inSeconds % 60).toString().padLeft(2, '0')} ',
                  style: const TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontSize: 11,
                    height: 1.3,
                  ),
                ),
                Text(
                  '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
                  style: const TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontSize: 11,
                    height: 1.3,
                  ),
                ),
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: previousSong,
                child: Image.asset(
                  'assets/images/last.png',
                  width: 29,
                  height: 25,
                ),
              ),
              const SizedBox(width: 37.5),
              GestureDetector(
                onTap: isPlaying ? pauseAudio : playAudio,
                child: Image.asset(
                  isPlaying
                      ? 'assets/images/stop.png'
                      : 'assets/images/play.png',
                  width: 55,
                  height: 55,
                ),
              ),
              const SizedBox(width: 37.5),
              GestureDetector(
                onTap: nextSong,
                child: Image.asset(
                  'assets/images/next.png',
                  width: 29,
                  height: 25,
                ),
              ),
            ],
          ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0),
              color: const Color(0xFF323851),
            ),
            margin: const EdgeInsets.fromLTRB(22, 40, 22, 22),
            child: Column(
              children: [
                const ListTile(
                  title: Text(
                    '歌词',
                    style: TextStyle(
                      color: Color(0xFF00E8C6),
                      fontSize: 14,
                      height: 1,
                    ),
                  ),
                ),
                for (final line in lyrics)
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 10.0, horizontal: 15.0),
                    child: Align(
                      alignment: Alignment.centerLeft, // 左对齐
                      child: Text(
                        line,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          height: 1.5,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
